import os,requests,json,time,schedule
from datetime import datetime
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()

class ApitableMonitor:
    def __init__(self):
        self.start=time.time()
        self.api_key = os.getenv("APITABLE_API_KEY")
        self.datasheet_ids = os.getenv("APITABLE_DATASHEET_IDS").split(",")
        # self.last_records = {}  # 存储上次的记录 {datasheet_id: records}

    def fetch_records(self, datasheet_id):
        """假装获取 Apitable 表格记录"""
        url = f"https://api.apitable.com/fusion/v1/datasheets/{datasheet_id}/records"
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        response = requests.get(url, headers=headers)
        print(f"Error fetching records:")
        if response.status_code == 200:
            return response.json().get("records", [])
        else:
            print(f"Error fetching records: {response.text}")
            return []

    def send_email_notification(self, subject, body):
        """发送邮件通知 注意：要求邮箱支持SMTP发送"""
        import smtplib
        from email.mime.text import MIMEText
        # 假设发送邮箱成功
        print("邮件通知发送成功")

    def check_changes(self):
        """假设表格有变化
        实际要fetch_records请求数据判断,然后更新last_records
        """
        if time.time()-self.start>1:
            message = f"表格数据已更新！\n更新时间: {datetime.now()}"
            print(message)
            self.send_email_notification("Apitable 数据更新", message)

    def run(self, interval_minutes=5):
        """启动定时任务"""
        schedule.every(interval_minutes).minutes.do(self.check_changes)
        print(f"Apitable 监控已启动，每 {interval_minutes} 分钟检查一次...")
        while True:
            schedule.run_pending()
            time.sleep(1)

if __name__ == "__main__":
    monitor = ApitableMonitor()
    monitor.run(interval_minutes=0.1)  # 默认每5分钟检查一次